package com.zlp.netty;

import com.zlp.netty.message.LoginRequestMessage;
import com.zlp.netty.message.MessageCodec;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author: zhulaiping
 * @time: 2022/9/11 21:18
 */
@Slf4j
public class AAA {

    public static void main(String[] args) throws Exception {
        EmbeddedChannel channel = new EmbeddedChannel();
        // 添加解码器，避免粘包半包问题
        channel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
        channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 12, 4, 0, 0));
        channel.pipeline().addLast(new MessageCodec());
        LoginRequestMessage user = new LoginRequestMessage("Nyima", "123");
        //编码
        //channel.writeOutbound(user);
        // 测试解码
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
        //解码之前先把信息准备好，
        new MessageCodec().encode(null, user, byteBuf);

        ByteBuf slice = byteBuf.slice(0, 100);
        slice.retain();
        ByteBuf slice1 = byteBuf.slice(100, byteBuf.readableBytes() - 100);
        channel.writeInbound(slice);//这边调用完slice时，会释放内存，所以需要增加一个引用计数
        channel.writeInbound(slice1);
    }
}
